package com.sample.library.glide

import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.widget.ImageView
import androidx.annotation.NonNull
import androidx.annotation.Nullable
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.target.Target.SIZE_ORIGINAL
import com.bumptech.glide.request.transition.Transition
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.interfaces.XPopupImageLoader
import com.sample.library.R
import com.sample.library.util.FileUtil
import com.sample.library.util.ToastUtil
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStream

object GlideDownload {

    fun downloadImage(context: Context, imageURL: String) {

        val dirPath: String = context.getExternalFilesDir(null)?.absolutePath + "/" + context.getString(R.string.app_name) + "/"
        val dir = File(dirPath)
        val fileName = imageURL.substring(imageURL.lastIndexOf('/') + 1)
        Glide.with(context).load(imageURL).into(object : CustomTarget<Drawable?>() {
            override fun onResourceReady(@NonNull resource: Drawable, @Nullable transition: Transition<in Drawable?>?) {
                val bitmap = (resource as BitmapDrawable).bitmap
                ToastUtil.show("Saving Image...")
                saveImage(context, bitmap, dir, fileName)
            }

            override fun onLoadCleared(@Nullable placeholder: Drawable?) {}
            override fun onLoadFailed(@Nullable errorDrawable: Drawable?) {
                super.onLoadFailed(errorDrawable)
                ToastUtil.show("Failed to Download Image! Please try again later.")
            }
        })
    }

    private fun saveImage(context: Context, image: Bitmap, storageDir: File, imageFileName: String) {
        var successDirCreated = false
        if (!storageDir.exists()) {
            successDirCreated = storageDir.mkdir()
        }
        if (successDirCreated) {
            val imageFile = File(storageDir, imageFileName)
            val savedImagePath = imageFile.absolutePath
            try {
                val fOut: OutputStream = FileOutputStream(imageFile)
                image.compress(Bitmap.CompressFormat.JPEG, 100, fOut)
                fOut.close()
                ToastUtil.show("Image Saved! ")

                XPopup.Builder(context).asImageViewer(null, savedImagePath, object : XPopupImageLoader {
                    override fun loadImage(position: Int, uri: Any, imageView: ImageView) {
                        Glide.with(imageView).load(uri).apply(RequestOptions().override(SIZE_ORIGINAL)).into(imageView)
                    }

                    override fun getImageFile(context: Context, uri: Any): File {
                        return Glide.with(context).downloadOnly().load(uri).submit().get();
                    }
                }).show()

            } catch (e: Exception) {
                ToastUtil.show("Error while saving image!")
                e.printStackTrace()
            }
        } else {
            ToastUtil.show("Failed to make folder!")
            FileUtil.deleteDirectory(storageDir)
        }
    }
}